<template>
  <div>
    <!-- 热门城市 -->
    <div class="hot-city" v-if="cityKwd.length === 0">
      <div class="hot-city-title">热门城市</div>
      <ul class="hot-city-list">
        <li class="hot-city-item" v-for="city in hotCityList" :key="city.cityId"
            @click="setCityInfo(city.cityId, city.name)">{{city.name}}</li>
      </ul>
    </div>
    <!-- 城市索引栏 -->
    <van-index-bar v-if="computedCityList.length > 0" :index-list="computedIndexList" highlight-color="#191a1b"
                   @select="showIndexIcon" :sticky="false">
      <template v-for="item in computedCityList">
        <van-index-anchor :key="item.index" :index="item.index" />
        <van-cell v-for="city in item.cells" :key="city.cityId" :title="city.name"
                  @click="setCityInfo(city.cityId, city.name)" />
      </template>
    </van-index-bar>
    <van-empty image="search" description="没有找到匹配的城市" v-else />
  </div>
</template>

<script>
import { IndexBar, IndexAnchor, Cell, Empty, Toast } from 'vant'
import { mapMutations } from 'vuex'
import { load, getTimestamp } from '@/utils'

export default {
  name: 'CityList',
  components: {
    [IndexBar.name]: IndexBar,
    [IndexAnchor.name]: IndexAnchor,
    [Cell.name]: Cell,
    [Empty.name]: Empty
  },
  props: {
    cityKwd: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      cityList: []
    }
  },
  computed: {
    computedCityList () {
      const cityList = this.cityList.filter((city) => {
        return (
          city.pinyin.toUpperCase().includes(this.cityKwd.toUpperCase()) ||
          city.name.toUpperCase().includes(this.cityKwd.toUpperCase())
        )
      })
      return this.transformCityList(cityList)
    },
    computedIndexList () {
      return this.computedCityList.reduce((item, next) => {
        if (next.cells.length > 0) item.push(next.index)
        return item
      }, [])
    },
    hotCityList () {
      return this.cityList.filter((city) => city.isHot)
    }
  },
  methods: {
    ...mapMutations('CityModule', ['setCityId', 'setCityName']),
    ...mapMutations('CinemaModule', ['setCinemaList']),
    // 转化返回的数据格式，以适配 Vant2 组件库中的 IndexBar 索引栏
    transformCityList (cities) {
      const letterList = []
      // 遍历生成 26 个英文大写字母，并存放到数组中
      for (let code = 65; code < 91; code++) {
        letterList.push(String.fromCharCode(code))
      }
      const newCityList = []
      // 遍历，分组取出以首字母拼音 A-Z 开头的城市，并存入数组
      letterList.forEach((letter) => {
        const cityArr = cities.filter((city) => {
          return city.pinyin.toUpperCase().startsWith(letter)
        })
        if (cityArr.length > 0) {
          newCityList.push({
            index: letter,
            cells: cityArr
          })
        }
      })
      return newCityList
    },
    // 设置城市信息，并刷新影院缓存
    setCityInfo (cityId, cityName) {
      this.setCityId(cityId)
      this.setCityName(cityName)
      this.setCinemaList([]) // 只有当切换城市时才清空 Vuex 中的影院列表
      this.$router.replace('/films/nowplaying')
    },
    // 选中索引区域展示通知气泡
    showIndexIcon (index) {
      Toast({
        message: index,
        duration: 500
      })
    }
  },
  mounted () {
    load({
      url: `/gateway?k=${getTimestamp()}`,
      headers: { 'X-Host': 'mall.film-ticket.city.list' }
    })
      .then((res) => {
        this.cityList = res.data.data.cities
      })
      .catch(() => {
        this.cityList = []
      })
  }
}
</script>

<style lang="scss" scoped>
.hot-city {
  width: calc(100vw - 30px);
  margin: 0 auto;
  .hot-city-title {
    height: 20px;
    line-height: 20px;
    font-size: 13px;
    color: #797d82;
    margin: 10px 0px;
  }
  .hot-city-list {
    display: flex;
    flex-wrap: wrap;
    .hot-city-item {
      width: 100px;
      height: 30px;
      font-size: 14px;
      color: #191a1b;
      text-align: center;
      line-height: 30px;
      background-color: #f4f4f4;
      margin: 0px 7.5px 15px;
      border-radius: 3px;
    }
  }
}
</style>
